package org.endy.leisure.diaTracker.controller

import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import kotlinx.coroutines.reactor.mono
import org.endy.leisure.diaTracker.entity.User
import org.endy.leisure.diaTracker.service.UserService
import org.endy.leisure.diaTracker.util.CommUtils
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono

@Tag(name = "用户管理接口", description = "用于用户注册、用户登陆")
@RestController
@RequestMapping("/user")
class UserController(private val userService: UserService) {

    private val logger = LoggerFactory.getLogger(UserController::class.java)

    @Operation(summary = "用户注册", description = "使用小程序openID授权注册")
    @PostMapping("/register")
    fun registerUser(@RequestBody request: UserRegisterRequest): Mono<WebResponse<String>> = mono {
        val passwordShoder = CommUtils.md5Sign(request.password!!)
        val user = userService.createUser(
            User(
                phone = request.phone,
                password = passwordShoder,
                nickname = request.nickname
            )
        )
        WebResponse.success("注册成功，用户信息：${user}")
    }

    @Operation(summary = "用户信息更新", description = "用于用户更新或者补充信息")
    @PostMapping("/update")
    fun updateUser(@RequestBody request: UserUpdateRequest): Mono<WebResponse<String>> = mono {

        val user = User(
            id = request.userId,
            password = request.password?.let { CommUtils.md5Sign(it) },
            nickname = request.nickname,
            avatar = request.avatar,
            roleType = request.roleType
        )
        userService.updateUser(user)
        WebResponse.success("用户${request.userId}更新成功")
    }

    @Operation(summary = "更改用户角色", description = "用于管理员更新用户的角色信息")
    @PostMapping("/changeRoleType")
    fun changeUserRole(@RequestBody request: ChangeUserRoleRequest): Mono<WebResponse<String>> = mono {
        val user = userService.updateUserRoleByPhone(request.phone, request.roleType)
        WebResponse.success("用户${user?.id}更新成功")
    }

    @Operation(summary = "用户登陆", description = "用于小程序使用openID进行登陆")
    @PostMapping("/login")
    fun login(@RequestBody request: UserRegisterRequest): Mono<WebResponse<User?>> =
        mono {
            val user = userService.login(null, request.phone!!)
            val passwordShoder = CommUtils.md5Sign(request.password!!)
            if (user != null && user.password == passwordShoder) {
                logger.info("用户登陆成功，用户信息：{}", user)
                WebResponse.success(user)
            } else {
                WebResponse.fail("用户不存在或者密码错误")
            }
        }

}